<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px" >
      <el-form-item label="部门名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属校区" prop="campus">
        <el-input
          v-model="queryParams.campus"
          placeholder="请输入所属校区"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="同级显示顺序" prop="orderNum" >-->
<!--        <el-input-->
<!--          v-model="queryParams.orderNum"-->
<!--          placeholder="请输入同级显示顺序"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label="负责人姓名" prop="leader" label-width="100px" >
        <el-input
          v-model="queryParams.leader"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <!-- 上级部门查询 -->
      <el-form-item label="查询上级部门" label-width="98px">
        <el-input
            v-model="queryParams2.deptName"
            placeholder="请输入部门名称"
            clearable
            :disabled="!!queryParams3.deptName"
            @keyup.enter="handleSmartQuery"
            @input="handleInput('parent')"
        />
      </el-form-item>

      <!-- 下级部门查询 -->
      <el-form-item label="查询下级部门" label-width="100px">
        <el-input
            v-model="queryParams3.deptName"
            placeholder="请输入部门名称"
            clearable
            :disabled="!!queryParams2.deptName"
            @keyup.enter="handleSmartQuery"
            @input="handleInput('child')"
        />
      </el-form-item>

      <el-form-item>
        <el-button
            type="primary"
            icon="Search"
            @click="handleSmartQuery"
            :disabled="!queryParams2.deptName && !queryParams3.deptName"
        >搜索</el-button>
        <el-button icon="Refresh" @click="resetSmartQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['cdutDept:dept:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Sort"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="部门名称" align="left" prop="deptName" />
      <el-table-column label="部门id" align="center" prop="deptId" />
<!--      <el-table-column label="父部门id" prop="parentId" />-->
      <el-table-column label="所属校区" align="center" prop="campus" />
<!--      <el-table-column label="负责人姓名" align="center" prop="leader" />-->
      <el-table-column label="状态：0-正常运营, 1-停用整顿" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cdutDept:dept:edit']">修改</el-button>
          <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['cdutDept:dept:add']">新增</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cdutDept:dept:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改成都大学部门对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父部门id" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="deptOptions"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择父部门id"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="所属校区" prop="campus">
          <el-input v-model="form.campus" placeholder="请输入所属校区" />
        </el-form-item>
        <el-form-item label="同级显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入同级显示顺序" />
        </el-form-item>
        <el-form-item label="负责人姓名" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="删除标记：0-存在, 2-已删除" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标记：0-存在, 2-已删除" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dept">
import {listDept, getDept, delDept, addDept, updateDept, parentDepartment,childrenDepartment} from "@/api/cdutDept/dept";

const { proxy } = getCurrentInstance();

const deptList = ref([]);
const deptOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    deptName: null,
    campus: null,
    orderNum: null,
    leader: null,
  },
  rules: {
  }
});
const data2= reactive({
  form2: {},
  queryParams2: {
    deptName: null,
  },
  rules2: {
  }
});
const data3= reactive({
  form3: {},
  queryParams3: {
    deptName: null,
  },
  rules3: {
  }
});
const { queryParams, form, rules } = toRefs(data);
const { queryParams2, form2, rules2 } = toRefs(data2);
const { queryParams3, form3, rules3 } = toRefs(data3);
const queryState = reactive({
  activeInput: null // 'parent' 或 'child'
})
/** 查询成都大学部门列表 */
function getList() {
  loading.value = true;
  listDept(queryParams.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId", "parentId");
    loading.value = false;
  });
}
/*查询上级部门*/
const getParentDepartment = () => {
  loading.value = true;
  parentDepartment(queryParams2.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId", "parentId");
    loading.value = false;
  });
}
/*查询下级部门*/
const getchildrenDepartment = () => {
  loading.value = true;
  childrenDepartment(queryParams3.value).then(response => {
    deptList.value = proxy.handleTree(response.data, "deptId", "parentId");
    loading.value = false;
  });
}

/** 查询成都大学部门下拉树结构 */
function getTreeselect() {
  listDept().then(response => {
    deptOptions.value = [];
    const data = { deptId: 0, deptName: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "deptId", "parentId");
    deptOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    deptId: null,
    parentId: null,
    ancestors: null,
    deptName: null,
    campus: null,
    orderNum: null,
    leader: null,
    phone: null,
    email: null,
    status: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}
// 智能查询方法
const handleSmartQuery = () => {
  if (queryParams2.value.deptName && queryParams3.value.deptName) {
    ElMessage.warning('请勿同时输入两个查询条件')
    return
  }

  if (queryParams2.value.deptName) {
    getParentDepartment()
  } else if (queryParams3.value.deptName) {
    getchildrenDepartment()
  } else {
    ElMessage.warning('请输入查询条件')
  }
}

// 输入框监听
const handleInput = (type) => {
  queryState.activeInput = type
  // 当检测到另一个输入框有值时清空
  if (type === 'parent' && queryParams3.value.deptName) {
    queryParams3.value.deptName = null
  }
  if (type === 'child' && queryParams2.value.deptName) {
    queryParams2.value.deptName = null
  }
}

// 智能重置方法
const resetSmartQuery = () => {
  queryParams2.value.deptName = null
  queryParams3.value.deptName = null
  queryState.activeInput = null
  // 可选：执行默认查询
  // handleSmartQuery()
}

// 添加监听器保证互斥
watch(() => queryParams2.value.deptName, (newVal) => {
  if (newVal) {
    queryParams3.value.deptName = null
  }
})

watch(() => queryParams3.value.deptName, (newVal) => {
  if (newVal) {
    queryParams2.value.deptName = null
  }
})
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.deptId) {
    form.value.parentId = row.deptId;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加成都大学部门";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getDept(row.deptId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改成都大学部门";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != null) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除成都大学部门编号为"' + row.deptId + '"的数据项？').then(function() {
    return delDept(row.deptId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>
